<html>
<head>
<title>任务管理</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>

<link rel="stylesheet" href="/static/css/stylemain.css">
<link rel="stylesheet" href="/static/layui/css/layui.css">

<link rel="stylesheet" href="/static/layui/css/treeTable.css">
<link rel="stylesheet" href="/static/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
<script src="/static/layui/layui.all.js"></script>
<script type="text/javascript" src="/static/js/jquery.js"></script>
<script type="text/javascript" src="/static/js/base64.js"></script>
</head>
<body>
<div class="layui-form">
  <table class="layui-hide" id="tbl_mission" lay-filter="tbl_mission"></table>
  <div id="page"></div>
  <script type="text/html" id="toolbarDemo">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm" lay-event="add"><i class="layui-icon layui-icon-add-circle"></i> 添加任务</button>
    <button class="layui-btn layui-btn-sm" lay-event="edit"><i class="layui-icon layui-icon-edit"></i> 编辑任务</button>
	<button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="stopmission"><i class="layui-icon layui-icon-404"></i> 终止任务</button>
	<input style="width:150px;height:24px;font-size: 12px;" id="orgsearch" class="ckinput" type="text" placeholder="机构名称查询"></input>
	<input style="width:150px;height:24px;font-size: 12px;margin-left:5px" id="ownersearch" class="ckinput" type="text" placeholder="所属人员查询"></input>
	<input style="width:150px;height:24px;font-size: 12px;margin-left:5px" id="locksnsearch" class="ckinput" type="text" placeholder="识别码查询"></input>
	<button type="button" id="btn_search" style="margin-left:5px" class="layui-btn layui-btn-primary layui-btn-xs" lay-event="search"><i class="fa fa-search" aria-hidden="true"></i>查询</button>
  </div>
  </script>
</div>
<input id="org_id" type="text" name="orgid" style="display:none"></input>
<script id="lockselect" type="text/html">
	<table class="layui-hide" id="tbl_locks" lay-filter="tbl_locks"></table>
</script>

<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">任务列表</a>
</script>

<script id="missionadd" type="text/html">
	<form class="layui-form" action="" style="margin-top:20px;width:660px;margin-left: 60px;">
		<div class="layui-form-item">
			<div class="layui-inline">
		    	<label class="layui-form-label">任务类型</label>
		    	<div class="layui-input-inline">
		       		<select name="mtype" id="mtype" lay-filter="mtype">
          				<option value="1">日常任务</option>						
          				<option value="0">应急任务</option>
						<option value="2">金库任务</option>
					</select>
		    	</div>
			</div>
			<div class="layui-inline">
	    		<label class="layui-form-label">指定机构</label>
		    	<div class="layui-input-inline">
		      		<input type="button" id="f_orgname" name="orgname" onclick="dialog_orgselect()" class="layui-input" style="text-align: left;">
		    	</div>	  			
			</div>
		  </div>		  
		<div class="layui-form-item" id="singlemission" style="display:none">
			<div class="layui-inline">
				<label class="layui-form-label">请选择锁具</label>
		    	<div class="layui-input-inline">
		      		<button type="button" id="slocks" name="slocks" onclick="dialog_lockselect1()" class="layui-input" style="text-align: left;"></button>
		    	</div>				
			</div>	
			<div class="layui-inline">
	    		<label class="layui-form-label">指定人员</label>
		   		<div class="layui-input-inline">
		      		<button type="button" id="lockauthuser" name="lockauthuser" onclick="dialog_findoperators()" class="layui-input" style="text-align: left;"></button>
		    	</div>
			</div>	
				
	  	</div>
		<div class="layui-form-item" id="multimission">
				<label class="layui-form-label">指定人员</label>
				<div class="layui-input-block" style="margin-right: 35px;">
					<button type="button" id="operators" name="operators" onclick="dialog_authselect()" class="layui-input" style="text-align: left;"></button>
				</div>
	  	</div>
		<div class="layui-form-item">
				<label class="layui-form-label">钥匙授权(分)</label>
				<div class="layui-input-block" style="margin-right: 35px;">
					<input type="text" id="keyvalid" name="keyvalid" lay-verify="number" class="layui-input" value="5">
				</div>
	  	</div>
		<div class="layui-form-item">
			<div class="layui-inline">
				<label class="layui-form-label">生效时间</label>
		    	<div class="layui-input-inline">
		      		<input type="text" class="layui-input" id="m_start" placeholder="yyyy-MM-dd HH:mm:ss">
		    	</div>
			</div>
			<div class="layui-inline">
				<label class="layui-form-label">终止时间</label>
		    	<div class="layui-input-inline">
		      		<input type="text" class="layui-input" id="m_end" placeholder="yyyy-MM-dd HH:mm:ss">
		    	</div>
			</div>
	    	
	  	</div>	  	
	  	<div class="layui-form-item">
	    	<label class="layui-form-label">备注</label>
		    <div class="layui-input-block" style="margin-right: 35px;">
		      <input type="text" id="descriptor" name="descriptor" class="layui-input">
		    </div>
	  	</div>			  	 
	</form>
</script>

<script type="text/javascript">
var table = layui.table;
var laypage = layui.laypage;
var laydate = layui.laydate;
var form = layui.form;
var curopt = "";
var _currpage = 1;
var _pageSize = 20;
var _sorgname = "";
var _sowner = "";
var _slocksn = "";
var _stopreason = "";
var _susername = "";
var _slocks = [];
var _sauthusers = [];

layui.use([], function(){
	getData(_currpage,_pageSize,"","","");

	form.on('select(users)', function(data){
		_susername = data.value;
		_slocks = [];		
	});
	
	form.on('select(mtype)', function(data){
		if(data.value == "1" || data.value == "2"){
			_slocks = [];
			$('#singlemission').css("display","none");
			$('#multimission').css("display","");
		}else{
			_sauthusers = [];
			$('#singlemission').css("display","");
			$('#multimission').css("display","none");
		}		
	});

	$('#ckpassword').on('keydown', function (event) {
	    if (event.keyCode == 13) {
	    	userckopt();
			layer.closeAll();
	    }
	});


	$("#org_id").on("input",function(e){
	    //获取input输入的值
	    var datastring = '{"orgid":"' + e.delegateTarget.value +'"}';
		debugger;
		$.ajax({
			type:"post",
			contentType: "application/json;charset=UTF-8",
			url: "getUserNamelist",
			async:false,
			data:datastring,
	     	dataType:"json",
	        success: function(msg) {    //数据提交成功时返回数据
	        	//debugger;
	        	if(msg.status == "1"){
	        		for(var i=0,l=msg.datas.length;i<l;i++){
	        			$("#users").append("<option value='"+msg.datas[i].username+"'>"+msg.datas[i].realname+"</option>");
	        		 }
	        		form.render('select');
	        	}else{
	        		layer.msg(msg.desc);
	        	}						
	        },
	        error : function(e){
	            alert(e.status);
	            alert(e.responseText);
	        }
	
		});		
	});
	
	table.on('toolbar(tbl_mission)', function(obj){
		//debugger;
		var checkStatus = table.checkStatus(obj.config.id);
	    switch(obj.event){
	      case 'add':
	    	  curopt = 'add';
	    	  dialog_add();
	      break;
	      case 'edit':
	    	  if(checkStatus.data.length == 0){
	      		layer.msg('请先选择任务!');
	      		return;
	      	  }
	    	  curopt = 'edit';
	    	  dialog_edit('','',checkStatus.data[0]);
	      break;  
	      case 'stopmission':
	    	  if(checkStatus.data.length == 0){
	      		layer.msg('请先选择任务!');
	      		return;
	      	  }
	    	  curopt = 'stopmission';
	    	  u_stop('','','');
	      break;  
	      case 'search':
	    	  curopt = 'search';
	    	  _currpage = 1;
	    	  getData(_currpage,_pageSize,$('#orgsearch').val().replace(/\s+/g,""),$('#ownersearch').val().replace(/\s+/g,""),$('#locksnsearch').val().replace(/\s+/g,""));
	      break; 
	    };
	    
	  });
	
	//监听工具条
	  table.on('tool(tbl_mission)', function(obj){
	    var data = obj.data;
	    if(obj.event === 'detail'){

	      layer.open({
			  type: 2 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
			  ,title: "任务列表" //标题
			  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
			  ,area: ['950px', '600px'] //宽度、高度
			  ,shade: 0.3
			  ,offset: 'auto'
			  ,anim:5 //弹出动画
			  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
			  ,content: 'template_mission_detail'     //内容
			  ,btn: ['确定']
			  ,success:function (layero,index) {
	              var iframe = window['layui-layer-iframe' + index];
	              debugger;
	              iframe.child(data.id,data.active);
	      	  }
			  ,yes: function(index, layero){
			    //按钮【按钮一】的回调
			    			    	
				 	layer.close(index);
			  }
			  ,cancel: function(index,layero){ 
				    //右上角关闭回调
			 }
	       });
	    }
	  });
});

function dialog_add(){
	_slocks = [];
	_sauthusers = [];
	var win = layer.open({
		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "添加任务" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['800px', '420px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: $("#missionadd").html()     //内容
		  ,btn: ['确定', '取消'] //只是为了演示
		  ,success:function(layero){
			     var mask = $(".layui-layer-shade");
			     mask.appendTo(layero.parent());
			     //$('#owner').removeAttr("disabled");
			     $('#f_orgname').removeAttr("disabled");
			     //$('#operators').removeAttr("disabled");
			     $('#slocks').removeAttr("disabled");
			     $('select').removeAttr('disabled');
			     laydate.render({
		    	    elem: '#m_start'
		    	    ,type: 'datetime'
		    	  });

			     laydate.render({
		    	    elem: '#m_end'
		    	    ,type: 'datetime'
		    	  });
			     form.render();
			}
		,yes: function(index, layero){
		    //按钮【按钮一】的回调
		    	//debugger;
		    	submitForm('','');
			 	 
		  }
		  ,btn2: function(index, layero){
		    //按钮【按钮二】的回调
		    
		    	//$("#useradd").css('display','none'); 
		    	
		  }
		  ,cancel: function(){ 
			    //右上角关闭回调
			    //$("#useradd").css('display','none'); 
			    
		 }
	});
}

function ckdialgo_auth(){
	layer.open({
		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "复核" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['350px', '260px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: $("#dlgck")     //内容
		  ,btn: ['确定', '取消'] //只是为了演示
		  ,success:function(layero){
			     //var mask = $(".layui-layer-shade");
			     //mask.appendTo(layero.parent());
			     $('#ckname').focus();
			     //其中：layero是弹层的DOM对象
			}
		 ,yes: function(index, layero){
		    //按钮【按钮一】的回调
		    	userckopt();
	    		$("#dlgck").css('display','none');
			 	layer.close(index);
		    	
			 	 
		  }
		  ,btn2: function(index, layero){
		    	//按钮【按钮二】的回调
		    
		    	$("#dlgck").css('display','none'); 
		    	
		  }
		  ,cancel: function(){ 
			    //右上角关闭回调
			    $("#dlgck").css('display','none'); 
			    
		 }
	});
}

function submitForm(ckname,ckpassword){
	debugger;
	if($('#mtype').val() == "1" || $('#mtype').val() == "2"){
		if(_sauthusers.length < 1){
			layer.msg("请填写任务指定人员!");
			return false;
		}
	}else if($('#mtype').val() == "0"){		
		if(_sauthusers.length < 1){
			layer.msg("请填写任务指定人员!");
			return false;
		}
		if(_slocks.length < 1){
			layer.msg("请选择任务指定的锁具!");
			return false;
		}
	}

	if(isNaN(Number($('#keyvalid').val()))){
		layer.msg("钥匙授权时间必须为整数!");
		return false;
	}
	
	if($('#m_start').val().length < 5){
		layer.msg("请填写任务开始时间!");
		return false;
	}
	if($('#m_end').val().length < 5){
		layer.msg("请填写任务终止时间!");
		return false;
	}
	
	var datastring = '{"stime":"' + $('#m_start').val() +'","etime":"' + $('#m_end').val()+'","orgid":"' + $('#org_id').val()+'","keyvalid":' + $('#keyvalid').val()
	+',"mtype":' + $('#mtype').val()+',"descriptor":"' + $('#descriptor').val()+ '","locks":' + JSON.stringify(_slocks) + ',"authuser":' + JSON.stringify(_sauthusers)+ ',"rname":"智能锁管理/任务管理/创建任务","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'"}';

	$.ajax({
		type:"post",
		contentType: "application/json;charset=UTF-8",
		url: "missionadd",
		async:false,
		data:datastring,
     	dataType:"json",
        success: function(msg) {    //数据提交成功时返回数据
        	debugger;
        	if(msg.status == "1"){
        		//clearForm();
        		getData(_currpage,_pageSize,$('#orgsearch').val().replace(/\s+/g,""),$('#ownersearch').val().replace(/\s+/g,""),$('#locksnsearch').val().replace(/\s+/g,""));
        		layer.closeAll();
        		_sorgname = $('#orgsearch').val();
        		_sowner = $('#ownersearch').val();
        		_slocksn = $('#locksnsearch').val();
        		//$("#useradd").css('display','none');
        	}else if(msg.status == "1211"){

        		$('#ckname').val('');
				$('#ckpassword').val('');
				ckdialgo_auth();
        		
        	}else{
        		layer.msg(msg.desc);
        	}						
        },
        error : function(e){
            alert(e.status);
            alert(e.responseText);
        }

	});		
}

function getData(pageNumber,pageSize,sorgname,sowner,locksn){
	_sorgname = sorgname;
	_sowner = sowner;
	_slocksn = locksn;
	var datastring = '{"pageNumber":'+pageNumber+',"pageSize":'+ pageSize + ',"orgname":"' + _sorgname + '","owner":"' + _sowner + '","locksn":"' + _slocksn + '","rname":"智能锁管理/任务管理/任务查询","ckname":"","ckpassword":""}';

	$.ajax({
		contentType: "application/json;charset=UTF-8",
		url : "getMissionlist",
		type : "post",
		data : datastring,
		dataType : "json",
		success : function(msg) {
			//debugger;
			if(msg.status == "1"){
				tablerender(msg);
				page(msg);
			}else{
				layer.msg(msg.desc);
			}		
			
		},
        error : function(e){
        	//dispalyEasyUILoad();
            alert(e.status);
            alert(e.responseText);
        }
	});
}

function tablerender(data){	
	table.render({
		  elem: '#tbl_mission'
		  ,toolbar: '#toolbarDemo'
		  ,cellMinWidth: 50
		  ,cols: [
			  [
			  {type:'radio', hide: true}
			,{field:'mtype', title: '任务类型', width:120, align: 'center', templet: '#statusTpl'}
			,{field:'stime', title: '生效时间', width:160}	
		    ,{field:'etime', title: '终止时间', width:160}		    
		    ,{field:'auth_reals', title: '授权人员', width:120}		    	
		    ,{field:'orgname', title: '所属机构', width:160}		    
		    ,{field:'active', title: '状态', width:60, align: 'center', templet: '#statusTpl2'}
		    ,{field:'keyvalid', title: '钥匙授权(分)', width:120}
		    ,{field:'stopreason', title: '终止原因', width:120}	
		    ,{field:'descriptor', title: '备注', width:120}
		    ,{field:'createtime', title: '创建时间', width:160} 
		    ,{field:'createname', title: '创建人', width:100}
		    ,{fixed: 'right', width:90, align:'center', toolbar: '#barDemo'}
		  ]
			  ]
		  ,data:data.datalist
		  ,limit: data.pageSize
		  ,height: parent.iframeH - 60,
		  done: function(res, curr, count){
		    $('#orgsearch').val(_sorgname);
		    $('#ownersearch').val(_sowner);
		    $('#locksnsearch').val(_slocksn);
		  }
		});	
	
	table.on('row(tbl_mission)', function(obj){
	    var data = obj.data;    
	    obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
		//选中radio样式
		obj.tr.find('i[class="layui-anim layui-icon"]').trigger("click");
	});
}

function numpage(pageNumber, pageSize) {
	var datastring = '{"pageNumber":'+pageNumber+',"pageSize":'+ pageSize + ',"orgname":"' + _sorgname + '","owner":"' + _sowner  + '","locksn":"' + _slocksn + '","rname":"智能锁管理/任务管理/任务查询","ckname":"","ckpassword":""}';
	//EasyUILoad();
	//debugger;
	$.ajax({
		contentType: "application/json;charset=UTF-8",
		url : "getMissionlist",
		type : "post",
		data : datastring,
		dataType : "json",
		success : function(msg) {
			//debugger;
			tablerender(msg);
		},
        error : function(e){
        	//dispalyEasyUILoad();
            alert(e.status);
            alert(e.responseText);
        }
	});
}

function page(data) {
    laypage.render({
        elem: 'page', //注意，这里的 page 是 ID，不用加 # 号
        count: data.totalCount, //数据总数，从服务端得到
        limit: data.pageSize,  // 每页条数
        limits: [10, 20, 30, 40, 50],
        layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
        curr: _currpage,
        jump: function (obj, first) {
            //console.log(obj)
            //obj包含了当前分页的所有参数，比如：
            //layer.msg(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
            //console.log(obj.limit); //得到每页显示的条数

            //首次不执行
            if (!first) {
                //do something
                _currpage = obj.curr;
                _pageSize = obj.limit;
                numpage(obj.curr, obj.limit)  // 分页点击传参 
            }
        }
    });
    form.render(); 
}

function dialog_edit(ckname,ckpassword,data){
	debugger;
	//获取已选信息
	
	if(data.mtype == 0){
		var lockinfo = {};
		lockinfo["locksn"] = data.locksn;
		_slocks = [];
		_slocks.push(lockinfo);
	}
	var authuserlist = data.authuser.split(",");
	var authuser_reallist = data.auth_reals.split(",");
	_sauthusers = [];
	for(i = 0;i<authuserlist.length;i++){
		var authinfo = {};
		authinfo["username"] = authuserlist[i];
		authinfo["oper_reals"] = authuser_reallist[i];
		//authinfo["roleid"] = authuser_reallist[i];
		_sauthusers.push(authinfo);
	}		
	var win = layer.open({
		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "编辑任务" //标题
		  ,skin:""   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['800px', '420px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: $("#missionadd").html()     //内容
		  ,btn: ['确定', '取消'] //只是为了演示
		  ,success:function(layero){
			     var mask = $(".layui-layer-shade");
			     mask.appendTo(layero.parent());
			     
			     //其中：layero是弹层的DOM对象
			     $('#f_orgname').val(data.orgname);
			     $('#org_id').val(data.orgid);
			     $('#keyvalid').val(data.keyvalid);
			     $("select[name='mtype']").val(data.mtype);
			     if(data.mtype == 1 || data.mtype == 2){
			    	 var appendhtml = "";
			    	 for(var i=0,l=_sauthusers.length;i<l;i++){
			    		if(i == 0){
			    			appendhtml += _sauthusers[i].oper_reals;
			    		}else{
			    			if(i < 6){
			    				appendhtml += "," + _sauthusers[i].oper_reals;
			    			}		
			    			if(i == 6){
			    				appendhtml += "...";
			    			}
			    		}
			    		
			    	 }
				     $('#operators')[0].innerHTML = '人数 <span class="layui-badge-rim">' + _sauthusers.length + '</span> :' + appendhtml;	
			    	 $('#singlemission').css("display","none");
					 $('#multimission').css("display","");
			     }else{		
			    	 var appendhtml = "";
			    	 for(var i=0,l=_slocks.length;i<l;i++){
			    		if(i == 0){
			    			appendhtml += _slocks[i].locksn;
			    		}else{
			    			if(i < 6){
			    				appendhtml += "," + _slocks[i].locksn;
			    			}		
			    			if(i == 6){
			    				appendhtml += "...";
			    			}
			    		}
			    		
			    	 }
			    	 $('#slocks')[0].innerHTML = appendhtml;
			    	 //$('#owner').attr("disabled","disabled");			    	 
			    	 $('#singlemission').css("display","");
					 $('#multimission').css("display","none");
					 $("#org_id").trigger("input");
					 $("#lockauthuser")[0].innerHTML = data.auth_reals;
					 
			     }
			     $('#f_orgname').attr("disabled","disabled");
			     $('#slocks').attr("disabled","disabled");
			     //$('#operators').attr("disabled","disabled");
			 	 $("#m_start").val(data.stime);
			 	 $("#m_end").val(data.etime);
			 	 $("#descriptor").val(data.descriptor);
			     
			     $('select').attr('disabled', 'disabled');
			     laydate.render({
		    	    elem: '#m_start'
		    	    ,type: 'datetime'
		    	  });

			     laydate.render({
		    	    elem: '#m_end'
		    	    ,type: 'datetime'
		    	  });
			     form.render(); 
			}
		  ,yes: function(index, layero){
		    //按钮【按钮一】的回调		    	
		    	u_edit('','');
			 	 
		  }
		  ,btn2: function(index, layero){
		    //按钮【按钮二】的回调
		    
		    	//$("#useradd").css('display','none'); 
		    	
		  }
		  ,cancel: function(){ 
			    //右上角关闭回调
			    //$("#useradd").css('display','none'); 
			    
		 }
	});
}

function u_edit(ckname,ckpassword){
	if($('#mtype').val() == "1" || $('#mtype').val() == "2"){
		if(_sauthusers.length < 1){
			layer.msg("请填写任务指定人员!");
			return false;
		}
	}else{		
		if(_sauthusers.length < 1){
			layer.msg("请填写任务指定人员!");
			return false;
		}
		if(_slocks.length < 1){
			layer.msg("请选择任务指定的锁具!");
			return false;
		}
	}
	if(isNaN(Number($('#keyvalid').val()))){
		layer.msg("钥匙授权时间必须为整数!");
		return false;
	}
	if($('#m_start').val().length < 5){
		layer.msg("请填写任务开始时间!");
		return false;
	}
	if($('#m_end').val().length < 5){
		layer.msg("请填写任务终止时间!");
		return false;
	}
	var userdata = table.checkStatus('tbl_mission');
	var row = userdata.data[0];
	
	debugger;
	var datastring = '{"missionid":"'+ row.id +'","stime":"' + $('#m_start').val() +'","etime":"' + $('#m_end').val()+'","keyvalid":' + $('#keyvalid').val()
	+',"mtype":' + $('#mtype').val()+',"descriptor":"' + $('#descriptor').val() + '","locks":' + JSON.stringify(_slocks) + ',"authuser":' + JSON.stringify(_sauthusers)+ ',"rname":"智能锁管理/任务管理/编辑任务","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'"}';
	$.ajax({
		type:"post",
		contentType: "application/json;charset=UTF-8",
		url: "missionedit",
		async:false,
		data:datastring,
     	dataType:"json",
        success: function(msg) {    //数据提交成功时返回数据
        	if(msg.status == "1"){        		
        		getData(_currpage,_pageSize,$('#orgsearch').val().replace(/\s+/g,""),$('#ownersearch').val().replace(/\s+/g,""),$('#locksnsearch').val().replace(/\s+/g,""));
        		layer.closeAll();
        		$("#missionadd").css('display','none');
        		clearForm();
        	}else if(msg.status == "1211"){
        		$('#ckname').val('');
				$('#ckpassword').val('');
				ckdialgo_auth();
        	}else{
        		layer.msg(msg.desc);
        	}						
        },
        error : function(e){
            alert(e.status);
            alert(e.responseText);
        }

	});	
}  

function u_stop(ckname,ckpassword,stopreason){
	var userdata = table.checkStatus('tbl_mission');
	var row = userdata.data[0];
	//debugger;
	if (row){
		if(row.active == 1){
			layer.alert('任务已终止,无需操作!', {icon: 7});
			return;
		}
		if(ckname == ''){
			layer.prompt({
				  formType: 2,
				  value: '',
				  title: '请输入终止原因',
				  area: ['300px', '30px'] //自定义文本域宽高
				}, function(value, index, elem){
					_stopreason = value;
					var datastring = '{"missionid":"'+ row.id + '","descriptor":"' + _stopreason + '","rname":"智能锁管理/任务管理/终止任务","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'"}';
					$.ajax({
						type:"post",
						contentType: "application/json;charset=UTF-8",
						url: "missionstop",
						async:false,
						data:datastring,
				     	dataType:"json",
				        success: function(msg) {    //数据提交成功时返回数据
				        	if(msg.status == "1"){        		
				        		getData(_currpage,_pageSize,$('#orgsearch').val().replace(/\s+/g,""),$('#ownersearch').val().replace(/\s+/g,""),$('#locksnsearch').val().replace(/\s+/g,""));
				        		layer.closeAll();
				        	}else if(msg.status == "1211"){
				        		$('#ckname').val('');
								$('#ckpassword').val('');
								ckdialgo_auth();
				        	}else{
				        		layer.msg(msg.desc);
				        	}						
				        },
				        error : function(e){
				            alert(e.status);
				            alert(e.responseText);
				        }

					});	
				    layer.close(index);
				}); 
			
		}else{
			var datastring = '{"missionid":"'+ row.id + '","descriptor":"' + stopreason + '","rname":"智能锁管理/任务管理/终止任务","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'"}';
			$.ajax({
				type:"post",
				contentType: "application/json;charset=UTF-8",
				url: "missionstop",
				async:false,
				data:datastring,
		     	dataType:"json",
		        success: function(msg) {    //数据提交成功时返回数据
		        	if(msg.status == "1"){        		
		        		getData(_currpage,_pageSize,$('#orgsearch').val().replace(/\s+/g,""),$('#ownersearch').val().replace(/\s+/g,""),$('#locksnsearch').val().replace(/\s+/g,""));
		        		layer.closeAll();
		        	}else if(msg.status == "1211"){
		        		$('#ckname').val('');
						$('#ckpassword').val('');
						ckdialgo_auth();
		        	}else{
		        		layer.msg(msg.desc);
		        	}						
		        },
		        error : function(e){
		            alert(e.status);
		            alert(e.responseText);
		        }

			});	
		}
							
	}else{
		layer.msg('需选择任务!');
	}
}  

function userckopt(){
	//debugger;
	var ckname = $('#ckname').val();
	if(ckname == ''){
		layer.msg('请填写用户账号!');
		return;
	}
	var ckpassword = $('#ckpassword').val();
	if(curopt == "add"){
		submitForm(ckname,$.base64.encode(ckpassword));
	}else if(curopt == "edit"){
		u_edit(ckname,$.base64.encode(ckpassword));
	}else if(curopt == "stopmission"){
		u_stop(ckname,$.base64.encode(ckpassword),_stopreason);
	}	
}

function userckopt_cancel(){
	$('#ckname').val('');
	$('#ckpassword').val('');	
}

function dialog_orgselect(){
	layer.open({
		  type: 2 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "选择机构" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['350px', '400px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: 'getorgtree'     //内容
		  ,btn: ['取消'] //只是为了演示		
		  ,success:function (layero,index) {
			  debugger;
              var iframe = window['layui-layer-iframe' + index];              
              iframe.child("lockmission_org","porg");
      	  }
		  ,yes: function(index, layero){
		    //按钮【按钮一】的回调
			 	 //$("#orgtree").css('display','none'); 
			 	layer.close(index);
		  }
		  ,cancel: function(index,layero){ 
			    //右上角关闭回调
			    //$("#orgtree").css('display','none'); 
		 }
       });
}

function dialog_lockselect(){
	layer.open({
		  type: 2 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "选择锁具" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['450px', '500px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: 'getlockstable'     //内容
		  ,btn: ['确定', '取消'] //只是为了演示	
		  ,success:function (layero,index) {
              var iframe = window['layui-layer-iframe' + index];
              iframe.child(_susername,_slocks);
      	  }
		  ,yes: function(index, layero){
		    //按钮【按钮一】的回调
			 	 //$("#orgtree").css('display','none'); 
		    	debugger;
		    	var iframeWin = window[layero.find('iframe')[0]['name']];
	        	_slocks = iframeWin.getCheckedLocks();

	        	$('#slocks')[0].innerHTML = '已选 <span class="layui-badge-rim">' + _slocks.length + '</span>';
			 	layer.close(index);
		  }
		  ,cancel: function(index,layero){ 
			    //右上角关闭回调
			    //$("#orgtree").css('display','none'); 
		 }
       });
}

function dialog_lockselect1(){
	layer.open({
		  type: 2 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "选择锁具" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['650px', '500px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: 'template_locklist'     //内容
		  ,btn: ['确定', '取消'] //只是为了演示	
		  ,success:function (layero,index) {
              var iframe = window['layui-layer-iframe' + index];
              iframe.child(_slocks,$('#org_id').val(),0);
      	  }
		  ,yes: function(index, layero){
		    //按钮【按钮一】的回调
			 	 //$("#orgtree").css('display','none'); 
		    	debugger;
		    	var iframeWin = window[layero.find('iframe')[0]['name']];
	        	_slocks = iframeWin.getCheckedLocks();
	        	var json;
	        	var operators = _slocks[0].operator.split(",");
	        	var oper_reals = _slocks[0].oper_reals.split(",");
	        	for(i=0;i<operators.length;i++){
	        		json = {};
	        		json["username"] = operators[i];
	        		json["oper_reals"] = oper_reals[i];
	        		_sauthusers.push(json);
	        	}
	        	
	        	$('#slocks')[0].innerHTML = _slocks[0].locksn;
	        	$('#lockauthuser')[0].innerHTML = _slocks[0].oper_reals;
			 	layer.close(index);
		  }
		  ,cancel: function(index,layero){ 
			    //右上角关闭回调
			    //$("#orgtree").css('display','none'); 
		 }
       });
}

function dialog_findoperators(){
	debugger;
	if(_slocks.length == 0){
  	  layer.msg('请先选择锁具!');
  	  return;
	}
	layer.open({
		  type: 2 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "选择授权人" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['550px', '600px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: 'template_userlistByLock'     //内容
		  ,btn: ['确定','取消'] //只是为了演示	
		  ,success:function (layero,index) {
			  debugger;
              var iframe = window['layui-layer-iframe' + index];
              iframe.child(_slocks[0].locksn,_sauthusers);
      	  }
		  ,yes: function(index, layero){
		    //按钮【按钮一】的回调
		    	iframeWin = window[layero.find('iframe')[0]['name']];
		    	_sauthusers = iframeWin.getCheckedUsers();	
		    	debugger;
		    	var appendhtml = "";
		    	for(var i=0,l=_sauthusers.length;i<l;i++){
		    		if(i == 0){
		    			appendhtml += _sauthusers[i].oper_reals;
		    		}else{
		    			if(i < 6){
		    				appendhtml += "," + _sauthusers[i].oper_reals;
		    			}		
		    			if(i == 6){
		    				appendhtml += "...";
		    			}
		    		}
		    		
		    	}
		    	$('#lockauthuser')[0].innerHTML = appendhtml;		    	
			 	layer.close(index);
		  }
		  ,cancel: function(index,layero){ 
			    //右上角关闭回调
		 }
       });
}

function dialog_authselect(){
	debugger;
	if($('#org_id').val() == ""){
  	  layer.msg('请先选择所属机构!');
  	  return;
	}
	layer.open({
		  type: 2 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "选择使用人" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['550px', '600px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: 'userlist'     //内容
		  ,btn: ['确定','取消'] //只是为了演示	
		  ,success:function (layero,index) {
			  debugger;
              var iframe = window['layui-layer-iframe' + index];
              iframe.child(_sauthusers,$('#org_id').val(),$('#mtype').val());
      	  }
		  ,yes: function(index, layero){
		    //按钮【按钮一】的回调
		    	iframeWin = window[layero.find('iframe')[0]['name']];
		    	_sauthusers = iframeWin.getCheckedUsers();	
		    	debugger;
		    	if($('#mtype').val() == "2" && _sauthusers.length > 2){
		    		layer.msg("金库任务授权人员为2人.");
		    		return;
		    	}
		    	var appendhtml = "";
		    	for(var i=0,l=_sauthusers.length;i<l;i++){
		    		if(i == 0){
		    			appendhtml += _sauthusers[i].oper_reals;
		    		}else{
		    			if(i < 9){
		    				appendhtml += "," + _sauthusers[i].oper_reals;
		    			}		
		    			if(i == 9){
		    				appendhtml += "...";
		    			}
		    		}
		    		
		    	}
		    	$('#operators')[0].innerHTML = '人数 <span class="layui-badge-rim">' + _sauthusers.length + '</span> :' + appendhtml;		    	
			 	layer.close(index);
		  }
		  ,cancel: function(index,layero){ 
			    //右上角关闭回调
		 }
       });
}
</script>
<script type="text/html" id="statusTpl">
  {{#  if(d.mtype == '0'){ }}	
    <span style="color: #ef40b1;">应急任务</span>
  {{#  } else if(d.mtype == '1') { }}
    <span">日常任务</span>
  {{#  } else if(d.mtype == '2') { }}
    <span">金库任务</span>
  {{#  } }}
</script>
<script type="text/html" id="statusTpl2">
  {{#  if(d.active == '0'){ }}	
    <span>正常</span>
  {{#  } else if(d.active == '1') { }}
    <span style="color: #F581B1;">终止</span>
  {{#  } }}
</script>
</body>
</html>
